﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace CreativeMinds.Umbraco.Installation {
	public class UIConfigInstaller {
		private XmlDocument originalConfig;
		private string originalConfigPath;
		private XmlDocument newConfig;

		public UIConfigInstaller(string originalConfigPath, string newConfigPath) {
			this.originalConfigPath = originalConfigPath;
			this.originalConfig = new XmlDocument();
			this.originalConfig.Load(this.originalConfigPath);

			this.newConfig = new XmlDocument();
			this.newConfig.Load(newConfigPath);
		}

		public void Merge() {
			XmlNode root = originalConfig.SelectSingleNode("./*");

			foreach (XmlNode node in newConfig.SelectNodes("./*/nodeType")) {
				XmlNode existingNode = root.SelectSingleNode(String.Format("nodeType[@alias='{0}']", node.Attributes.GetNamedItem("alias").Value));
				if (existingNode != null) {
					existingNode.InnerXml = node.InnerXml;
				}
				else {
					existingNode = originalConfig.CreateElement("nodeType");
					root.AppendChild(existingNode);

					XmlAttribute aliasAttr = originalConfig.CreateAttribute("alias");
					existingNode.Attributes.Append(aliasAttr);
					aliasAttr.Value = node.Attributes.GetNamedItem("alias").Value;

					existingNode.InnerXml = node.InnerXml;
				}
			}

			this.originalConfig.Save(this.originalConfigPath);
		}
	}
}